package com.jifeng.api.crud.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jifeng.api.crud.dao.FeeConfigDao;
import com.jifeng.api.crud.entity.FeeConfigEntity;
import com.jifeng.api.crud.service.FeeConfigService;
import com.jifeng.api.utils.PageUtils;
import com.jifeng.api.utils.Query;
import com.jifeng.api.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Map;
import java.util.Objects;


@Service("feeConfigService")
@Slf4j
public class FeeConfigServiceImpl extends ServiceImpl<FeeConfigDao, FeeConfigEntity> implements FeeConfigService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<FeeConfigEntity> page = this.page(
                new Query<FeeConfigEntity>().getPage(params),
                new QueryWrapper<FeeConfigEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R getFeeConfig() {
        try {
            FeeConfigEntity feeConfigEntity = this.getById(1);
            return R.ok().put("data", feeConfigEntity);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("path：{}，errMsg：{}", getRequestUrl(), e.getMessage());
            return R.sysError();
        }
    }

    @Override
    public R myUpdateById(FeeConfigEntity feeConfig) {
        try {
            boolean updateRs = this.updateById(feeConfig);
            if (updateRs) {
                return R.ok();
            }
            return R.error();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("path：{}，errMsg：{}", getRequestUrl(), e.getMessage());
            return R.sysError();
        }

    }

    @Override
    public R updateConfig(FeeConfigEntity feeConfig) {
        try {
            feeConfig.setId(1L);
            boolean update = this.updateById(feeConfig);
            if (!update) {
                log.warn("path：{}，errMsg：{}，cause：{}", getRequestUrl(), "更新费用配置失败", "所传参数出现问题");
                return R.error("更新费用配置失败");
            }
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("path：{}，errMsg：{}", getRequestUrl(), e.getMessage());
            return R.sysError();
        }
    }

    public String getRequestUrl() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest().getRequestURI();
    }
}